{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "98893b93",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "8244f6e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import LlamaConfig, LlamaForCausalLM, AutoTokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1dfd60f1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaConfig {\n",
       "  \"_name_or_path\": \"mesolitica/llama-7b-hf-16384-fpf\",\n",
       "  \"architectures\": [\n",
       "    \"LlamaForCausalLM\"\n",
       "  ],\n",
       "  \"bos_token_id\": 1,\n",
       "  \"eos_token_id\": 2,\n",
       "  \"hidden_act\": \"silu\",\n",
       "  \"hidden_size\": 4096,\n",
       "  \"initializer_range\": 0.02,\n",
       "  \"intermediate_size\": 11008,\n",
       "  \"max_position_embeddings\": 32768,\n",
       "  \"model_type\": \"llama\",\n",
       "  \"num_attention_heads\": 32,\n",
       "  \"num_hidden_layers\": 4,\n",
       "  \"num_key_value_heads\": 32,\n",
       "  \"pad_token_id\": 0,\n",
       "  \"pretraining_tp\": 1,\n",
       "  \"rms_norm_eps\": 1e-05,\n",
       "  \"rope_scaling\": null,\n",
       "  \"tie_word_embeddings\": false,\n",
       "  \"torch_dtype\": \"bfloat16\",\n",
       "  \"transformers_version\": \"4.31.0\",\n",
       "  \"use_cache\": true,\n",
       "  \"vocab_size\": 32000\n",
       "}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half_config = LlamaConfig.from_pretrained('fpf-7b-32k/checkpoint-7400', \n",
    "                                             num_hidden_layers = 4)\n",
    "half_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "6f18862a",
   "metadata": {},
   "outputs": [],
   "source": [
    "small = LlamaForCausalLM(half_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "763f48e7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaForCausalLM(\n",
       "  (model): LlamaModel(\n",
       "    (embed_tokens): Embedding(32000, 4096, padding_idx=0)\n",
       "    (layers): ModuleList(\n",
       "      (0-3): 4 x LlamaDecoderLayer(\n",
       "        (self_attn): LlamaAttention(\n",
       "          (q_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (k_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (v_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (o_proj): Linear(in_features=4096, out_features=4096, bias=False)\n",
       "          (rotary_emb): LlamaRotaryEmbedding()\n",
       "        )\n",
       "        (mlp): LlamaMLP(\n",
       "          (gate_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "          (up_proj): Linear(in_features=4096, out_features=11008, bias=False)\n",
       "          (down_proj): Linear(in_features=11008, out_features=4096, bias=False)\n",
       "          (act_fn): SiLUActivation()\n",
       "        )\n",
       "        (input_layernorm): LlamaRMSNorm()\n",
       "        (post_attention_layernorm): LlamaRMSNorm()\n",
       "      )\n",
       "    )\n",
       "    (norm): LlamaRMSNorm()\n",
       "  )\n",
       "  (lm_head): Linear(in_features=4096, out_features=32000, bias=False)\n",
       ")"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f5a91bb0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1071681536"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(p.numel() for p in small.parameters())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e2a42276",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "37a4cfc052a84ba4983f838fab921e1b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading checkpoint shards:   0%|          | 0/2 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "model = LlamaForCausalLM.from_pretrained('fpf-7b-32k/checkpoint-7400')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a4040b8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "def copy_layers(src_layers, dest_layers, layers_to_copy):\n",
    "    layers_to_copy = nn.ModuleList([src_layers[i] for i in layers_to_copy])\n",
    "    assert len(dest_layers) == len(layers_to_copy), f\"{len(dest_layers)} != {len(layers_to_copy)}\"\n",
    "    dest_layers.load_state_dict(layers_to_copy.state_dict())\n",
    "\n",
    "layers_to_copy = [0,1,2,3]\n",
    "\n",
    "copy_layers(model.model.layers, small.model.layers, layers_to_copy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "57a02088",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.embed_tokens.load_state_dict(model.model.embed_tokens.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "10842eb0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.norm.load_state_dict(model.model.norm.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b42aec08",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.lm_head.load_state_dict(model.lm_head.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f5e2de4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "small.save_pretrained(\"1b\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "dc8e1762",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('1b/tokenizer_config.json', '1b/special_tokens_map.json', '1b/tokenizer.json')"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained('fpf-7b-32k/checkpoint-7400')\n",
    "tokenizer.save_pretrained(\"1b\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c15d1056",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "total 4.0G\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  633 Sep 17 06:14 config.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  132 Sep 17 06:14 generation_config.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu 4.0G Sep 17 06:14 pytorch_model.bin\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  414 Sep 17 06:14 special_tokens_map.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu 1.8M Sep 17 06:14 tokenizer.json\r\n",
      "-rw-r--r-- 1 ubuntu ubuntu  725 Sep 17 06:14 tokenizer_config.json\r\n"
     ]
    }
   ],
   "source": [
    "!ls -lh 1b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9b5b3e6",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
